package com.reborn.mall.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.reborn.mall.api.common.util.AliyunOSSUtil;
import com.reborn.mall.api.common.util.BeanUtil;
import com.reborn.mall.api.mybatis.mapper.ProductMapper;
import com.reborn.mall.api.model.dto.ProductDTO;
import com.reborn.mall.api.model.entity.Product;
import com.reborn.mall.api.model.entity.ProductAttributeValue;
import com.reborn.mall.api.model.vo.ProductVO;
import com.reborn.mall.api.service.ProductAttributeValueService;
import com.reborn.mall.api.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * TODO: Here is description
 *
 * @author wu.yue
 * @since 2020/1/23
 */
@Service
public class ProductServiceImpl extends BaseServiceImpl<Product> implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    @Autowired
    private ProductAttributeValueService attributeValueService;

    @Override
    public int createProduct(ProductDTO productDTO) {
        Long productId = insertProduct(productDTO);
        int insertRowCount = insertProductAttrValues(productId, productDTO.getAttributeValues());
        return insertRowCount;
    }

    @Override
    public ProductVO getProductDetails(Long id) {
        Product product = super.findById(id);
        List<ProductAttributeValue> params = productMapper.getProductParams(id);
        List<ProductAttributeValue> specifications = productMapper.getProductSpecifications(id);
        ProductVO productVO = BeanUtil.copyProperties(product, ProductVO.class);
        productVO.setParams(params);
        productVO.setSpecifications(specifications);
        return productVO;
    }

    /**
     * 插入商品基本信息
     * @param productDTO 商品传输DTO对象
     * @return 商品ID
     */
    private Long insertProduct(ProductDTO productDTO) {
        String attributeValuesJson = productDTO.getAttributeValues();
        List<ProductAttributeValue> attributeValues = JSON.parseArray(attributeValuesJson, ProductAttributeValue.class);
        Product product = BeanUtil.copyProperties(productDTO, Product.class);
        if (productDTO.getFileList() != null) {
            List<String> fileList = aliyunOSSUtil.uploadFile(productDTO.getFileList());
            product.setAlbumPics(String.join(",", fileList));
        }
        insertSelective(product);
        return product.getId();
    }

    /**
     * 插入商品属性值
     * @param productId 商品ID
     * @param attrValuesJson 属性值数组JSON
     * @return 插入行数
     */
    private int insertProductAttrValues(Long productId, String attrValuesJson) {
        List<ProductAttributeValue> attributeValues = JSON.parseArray(attrValuesJson, ProductAttributeValue.class);
        attributeValues.forEach(each -> each.setProductId(productId));

        return attributeValueService.insertBatch(attributeValues);
    }
}
